#include <stdio.h>
#include <stdlib.h>
#include "network.h"

void error_if(int condition, char * message) 
{
  if (condition) {
    printf("ERROR: %s\nMessage: ", message);
    perror(""); 
    exit(1);
  } 
}


int is_ip_valid(char * url)
{
  char c;
  int i, ip[4];
  int result = sscanf(url, "%d.%d.%d.%d%c", &ip[0], &ip[1], &ip[2], &ip[3], &c);

  if (result != 4)
    return 0;

  for (i = 0; i < 4; i++)
    if (ip[i] < 0 || ip[i] > 255)
      return 0;

  return 1;
}

void url_to_adress(char * url, short port, struct sockaddr_in * adress)
{    
  adress->sin_family = AF_INET;
  adress->sin_port = htons(port);
  if (is_ip_valid(url)) {
    adress->sin_addr.s_addr = inet_addr(url);  
  } else {
    struct hostent *resolv = gethostbyname(url);
    error_if(resolv == 0, "Unable to resolve adress");
    adress->sin_addr.s_addr = *(long*)resolv->h_addr;
  }
}

int socket_open(char * url, short port) 
{
  int socket_id = socket(AF_INET, SOCK_STREAM, 0);
  error_if(socket_id < 0, "Unanable to create socket");

  struct sockaddr_in adress;
  url_to_adress(url, port, &adress);

  int connect_result = connect(socket_id, (struct sockaddr*)&adress, sizeof(struct sockaddr_in));
  error_if(connect_result < 0, "Unanable to connect");

  return socket_id;
}



